package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseSectionQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.ExercisesWeekly;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.topic.DailyPracticeActivity;
import com.zahb.qadx.ui.view.BorderTextView;
import com.zahb.qadx.util.ClickCheck;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.PackageUtils;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 答题练习-每周练习
 */
public class AnswerExercisesWeeklyActivity extends BaseActivity implements OnItemChildClickListener {

    private BaseSectionQuickAdapter<ExercisesWeekly, BaseViewHolder> mAdapter;
    private OptionsPickerView<String> mPickerView;
    private int mIsDefault, mYear, mMonth;
    private boolean mHasClickToNewPage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWeeklyPracticeMinTime();
        getWeeklyPracticeList(0, 0, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mHasClickToNewPage) {
            mHasClickToNewPage = false;
            getWeeklyPracticeList(mIsDefault, mYear, mMonth);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_answer_exercises_weekly;
    }

    @Override
    protected void initViews() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, DisplayUtil.dip2px(16f));
            }
        });
        mAdapter = new BaseSectionQuickAdapter<ExercisesWeekly, BaseViewHolder>(
                R.layout.item_list_exercises_weekly_header, R.layout.item_list_exercises_weekly, null) {
            @Override
            protected void convertHeader(@NotNull BaseViewHolder baseViewHolder, @NotNull ExercisesWeekly item) {
                baseViewHolder.setText(R.id.tv_time, new StringBuilder().append(item.getCreateMonth()).append("月"))
                        .setTextColor(R.id.tv_time, Color.parseColor("#4C87FF"));
            }
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, ExercisesWeekly item) {
                TextView tvName = baseViewHolder.getView(R.id.tv_name);
                tvName.setText(String.format(Locale.getDefault(), "%d年%d月第%d周练习",
                        item.getCreateYear(), item.getCreateMonth(), item.getCreateWeek()));
                BorderTextView tvState = baseViewHolder.getView(R.id.tv_state);
                tvState.setText(item.getIsStart() == 0 ? "未答题" : "已答题");
                tvState.setTextColor(item.getIsStart() == 0 ? Color.parseColor("#4C87FF") : Color.parseColor("#999999"));
                tvState.setBorderColor(item.getIsStart() == 0 ? Color.parseColor("#E7EFFF") : Color.parseColor("#ECECEC"))
                        .setCornerRadius(DisplayUtil.dip2px(2f))
                        .setFill(true);
            }
        };
        //数据为空的时候
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mAdapter.setEmptyView(emptyView);
        mAdapter.addChildClickViewIds(R.id.tv_button);
        mAdapter.setOnItemChildClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.answer_exercises;
    }

    private void getWeeklyPracticeMinTime() {
        addDisposable(RetrofitService.getNetService()
                .getWeeklyPracticeMinTime()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        addSelectButton(response.getData());
                    }
                }, Throwable::printStackTrace));
    }

    private TextView mSelectView;

    private void addSelectButton(ExercisesWeekly weekly) {
        if (weekly == null) {
            return;
        }
        mSelectView = new TextView(getContext());
        mSelectView.setText("三月内");
        mSelectView.setTextSize(14f);
        mSelectView.setTextColor(Color.parseColor("#8A8A8A"));
        mSelectView.setGravity(Gravity.END | Gravity.CENTER_VERTICAL);
        mSelectView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_month_select, 0);
        ViewCompat.setPaddingRelative(mSelectView, 0, 0, DisplayUtil.dip2px2(18f), 0);
        mTopBarContainer.addView(mSelectView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mSelectView.getLayoutParams();
        lp.gravity = Gravity.END | Gravity.CENTER_VERTICAL;
        mSelectView.setLayoutParams(lp);

        mSelectView.setOnClickListener(v -> showSelectDialog(weekly));
    }

    private void showSelectDialog(ExercisesWeekly weekly) {
        if (mPickerView == null) {
            Calendar calendar = Calendar.getInstance();
            List<String> yearList = new ArrayList<>();
            List<List<String>> monthList = new ArrayList<>();
            yearList.add("三月内");
            monthList.add(new ArrayList<>());
            for (int year = calendar.get(Calendar.YEAR); year >= weekly.getCreateYear(); year--) {
                yearList.add("" + year);
                int start = 1;
                int end = 12;
                if (year == weekly.getCreateYear()) {// 开始年份
                    start = weekly.getCreateMonth();
                }
                if (year == calendar.get(Calendar.YEAR)) {// 结束年份
                    end = calendar.get(Calendar.MONTH) + 1;
                }
                List<String> items = new ArrayList<>();
                for (int month = end; month >= start; month--) {
                    if (month > 9)
                        items.add("" + month);
                    else
                        items.add("0" + month);
                }
                monthList.add(items);
            }
            mPickerView = new OptionsPickerBuilder(getContext(), (options1, options2, options3, v) -> {
                if (yearList.get(options1).equals("三月内")) {
                    mSelectView.setText("三月内");
                    getWeeklyPracticeList(0, 0, 0);
                } else {
                    mSelectView.setText(new StringBuilder().append(yearList.get(options1))
                            .append("-").append(monthList.get(options1).get(options2)));
                    int month = Integer.valueOf(monthList.get(options1).get(options2));
                    int year = Integer.valueOf(yearList.get(options1));
                    getWeeklyPracticeList(1, year, month);
                }
            }).setTitleText("月份筛选").build();
            mPickerView.setPicker(yearList, monthList);
        }
        mPickerView.show();
    }

    private void getWeeklyPracticeList(int isDefault, int year, int month) {
        mIsDefault = isDefault;
        mYear = year;
        mMonth = month;
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .getWeeklyPracticeList(isDefault, year, month)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (response.getData() == null || response.getData().isEmpty()) {
                            mAdapter.setList(new ArrayList<>());
                        } else {
                            handleMonthData(response.getData());
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void handleMonthData(List<ExercisesWeekly> list) {
        mAdapter.setList(new ArrayList<>());
        for (int i = 0; i < list.size(); i++) {
            int position = mAdapter.getData().size() - 1;
            if (mAdapter.getData().isEmpty() || mAdapter.getItem(position).getCreateMonth() != list.get(i).getCreateMonth()) {
                ExercisesWeekly header = new ExercisesWeekly();
                header.setCreateYear(list.get(i).getCreateYear());
                header.setCreateMonth(list.get(i).getCreateMonth());
                header.setCreateWeek(list.get(i).getCreateWeek());
                mAdapter.addData(header);
            }
            mAdapter.addData(list.get(i));
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (ClickCheck.isFastClick()) return;
        if (view.getId() == R.id.tv_button) {
            try {
                String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                String url = WebViewHelper.getBaseUrl() + "propaganda/practiceQuestion?fromType=1&token=" + token +
                        "&version=" + PackageUtils.getVersionName(getContext()) + "&exerciseType=2&Id=" + mAdapter.getItem(position).getId();
                Log.e("每周一练", url);
                SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
                int isAmazing = settingss.getInt("tryToSwitch", 0);
                if (isAmazing == 2) {
                    Intent intent = new Intent(AnswerExercisesWeeklyActivity.this, DailyPracticeActivity.class);
                    intent.putExtra("id", mAdapter.getItem(position).getId() + "");
                    intent.putExtra("path", 1);
                    startActivity(intent);
                } else {
                    MyWebViewActivity.actionStart(getContext(), url, "每周一练", 1);
                }
                if (mAdapter.getItem(position).getIsStart() == 0)
                    mHasClickToNewPage = true;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
